package com.generator.service;

import com.alibaba.fastjson.JSONObject;
import com.generator.common.CodeMsg;
import com.generator.common.CommonResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import java.util.ArrayList;
import java.util.List;

import static com.baomidou.mybatisplus.generator.config.rules.DateType.ONLY_DATE;

/**
 * Created by IntelliJ IDEA.
 * User : andylin
 * Date : 2021/4/10
 * Time : 9:04
 * 注意代码的层次与规范
 */
@Service
public class UserService {

    public CommonResult getCode(JSONObject params){


        String mysqlIp = params.getString("mysqlIp");
        String mysqlDatabase =  params.getString("mysqlDatabase");
        String author =  params.getString("author");

        String mysqlUserName =  params.getString("mysqlUserName");
        String mysqlPassword =  params.getString("mysqlPassword");
        String packageName =  params.getString("packageName");

        String tableName =  params.getString("tableName");


        if (mysqlIp == null || StringUtils.isBlank(mysqlIp)){
            return CommonResult.failMsg("mysqlIp 不能为空");
        }

        if (mysqlDatabase == null || StringUtils.isBlank(mysqlDatabase)){
            return CommonResult.failMsg("mysqlDatabase 不能为空");
        }
        if (author == null || StringUtils.isBlank(author)){
            return CommonResult.failMsg("author 不能为空");
        }

        if (mysqlUserName == null || StringUtils.isBlank(mysqlUserName)){
            return CommonResult.failMsg("mysqlUserName 不能为空");
        }
        if (mysqlPassword == null || StringUtils.isBlank(mysqlPassword)){
            return CommonResult.failMsg("mysqlPassword 不能为空");
        }
        if (packageName == null || StringUtils.isBlank(packageName)){
            return CommonResult.failMsg("packageName 不能为空");
        }

        String MYSQL_URL = "jdbc:mysql://"+mysqlIp+":3306/"+mysqlDatabase+"?useUnicode=true&characterEncoding=utf-8";

        System.out.println(MYSQL_URL);


        // 1、创建代码生成器
        AutoGenerator mpg = new AutoGenerator();
        // 2、全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/src/main/java");
        //设置作者
        gc.setAuthor(author);
        //生成后是否打开资源管理器
        gc.setOpen(false);
        //重新生成时文件是否覆盖
        gc.setFileOverride(true);
        //去掉Service接口的首字母I
        gc.setServiceName("%sService");
        //主键策略
        gc.setIdType(IdType.AUTO);
        //设置日期字段格式
        gc.setDateType(ONLY_DATE);
        mpg.setGlobalConfig(gc);
        // 3、数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(MYSQL_URL);
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername(mysqlUserName);
        dsc.setPassword(mysqlPassword);
        dsc.setDbType(DbType.MYSQL);
        mpg.setDataSource(dsc);
        // 4、包配置
        PackageConfig pc = new PackageConfig();
        //模块名
        pc.setModuleName(null);
        pc.setParent(packageName);
        pc.setController("controller");
        pc.setEntity("dao");
        pc.setService("service");
        pc.setMapper("mapper");
//        pc.setXml(null);
        mpg.setPackageInfo(pc);
        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };
        List<FileOutConfig> focList = new ArrayList<>();
        focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 将xml文件指定到特殊路径
                return projectPath + "/src/main/resources/mapper/"
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
        // 5、策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setEntityTableFieldAnnotationEnable(true);
        strategy.setEntitySerialVersionUID(false);
        //对那一张表生成代码 ,不设置代码数据库所有的表
        //如果传入的值为*表示生成这个数据库所有的表，则不用设置，否则指定表生成


        if (tableName == null || StringUtils.isBlank(tableName)){

        }else{
            strategy.setInclude(tableName);
        }

//        strategy.setInclude("customer,delivery,deliverydetails,parts,stock");
        //数据库表映射到实体的命名策略
        strategy.setNaming(NamingStrategy.underline_to_camel);
        //生成实体时去掉表前缀
        strategy.setTablePrefix(pc.getModuleName() + "_");
        //数据库表字段映射到实体的命名策略
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        // lombok 模型 @Accessors(chain = true) setter链式操作
        strategy.setEntityLombokModel(true);
        //restful api风格控制器
        strategy.setRestControllerStyle(true);
        //url中驼峰转连字符
        strategy.setControllerMappingHyphenStyle(true);
        mpg.setStrategy(strategy);
        TemplateConfig tc = new TemplateConfig();
        /**取消生成Service层代码*/
        tc.setService(null);
        tc.setServiceImpl(null);
        /***
         * 使用自定义格式生成实体类，自定义配置文件在src/main/resources/templates/entity.java.vm
         * */
        tc.setEntity("/templates/entity.java.vm");
        tc.setXml(null);
        // tc.setMapper("/templates/mapper.java.vm");
        /**取消生成controller代码*/
        tc.setController(null);
        // tc.setXml("/templates/mapper.xml.vm");
        mpg.setTemplate(tc);
        // 6、执行
        try {
            mpg.execute();
        } catch (Exception e) {

            e.printStackTrace();
            return CommonResult.failMsg(e.getMessage());
        }


        return CommonResult.ok();
    }

}
